import fs from 'fs'
import path from 'path'
import {
  wrapFn
} from './share/index'

import * as methodList from './uni-id'
class UniID {
  constructor () {
    this.config = {}
    try {
      this.config = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'config.json')))
    } catch (error) {}
  }

  init (config) {
    this.config = config
  }

  _getConfig (platform) {
    const platformConfig = Object.assign(this.config, this.config[platform || __ctx__.PLATFORM]) || {}
    const defaultConfig = {
      bindTokenToDevice: true
    }
    const config = Object.assign(defaultConfig, platformConfig)
    const argsRequired = ['passwordSecret', 'tokenSecret', 'tokenExpiresIn', 'passwordErrorLimit', 'passwordErrorRetryTime']
    argsRequired.forEach((item) => {
      if (!config || !config[item]) {
        throw new Error(`请在公用模块uni-id的config.json或init方法中内添加配置项：${item}`)
      }
    })
    return config
  }
}

for (const key in methodList) {
  UniID.prototype[key] = wrapFn(methodList[key])
}

const uniIDOrigin = new UniID()
const uniID = new Proxy(uniIDOrigin, {
  get (target, prop) {
    if (prop in target) {
      if (typeof target[prop] === 'function') {
        return target[prop].bind(uniID)
      } else {
        return target[prop]
      }
    }
  }
})

export default uniID
